#!/usr/bin/perl
#
# Login script for administrators
# No parameters - uses $ENV{REMOTE_USER} to find user entry.
# Does not require a password.
# Parameters:
# - url to redirect to
#
use Counter::CGI;
use MD5Cookies;
use Counter;
use CounterCGI;
use ErrorForm;
use CGI::Carp;
use POSIX qw(strftime);  

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8

$q = new Counter::CGI;

$tourl = $q->param("url");
if (!$tourl) {
    $tourl = "https://$ENV{HTTP_HOST}/adm/";
}
$testcookie = $q->cookie("cookiesenabled");
if (!$testcookie) {
    # test if this is THE problem
    # later version will have an error message here
    warn "User $userid [$ENV{REMOTE_ADDR}] appears not to have cookie support\n";
}
$inputid = $userid;
$userid =~ s/\s+$//; # strip trailing spaces

$users = Counter::open();
$inputid = $ENV{"REMOTE_USER"};
$user = $users->getbykey("login", $inputid);
if (!$user) {
    warn "Login user $inputid failed - bad userid\n";
    errorForm("no such user", $inputid);
}


# Thaw the user if he is frozen, mark OK if he is bad
if ($user->{state} eq "frozen") {
    warn "User $userid thawed\n";
    $user->thaw();
}
if ($user->{state} eq "bad") {
    $user->{state} = "ok";
}

# Note that the user is logged in
$user->{logintime} = strftime "%Y-%m-%d %H:%M:%S", gmtime();
$user->store();

warn "Login $userid [$ENV{REMOTE_ADDR}] identified by HTTP user\n";

$logincookie = CounterCGI::logincookie($user, $q);

if (!$testcookie) {
    #errorForm("no cookies", $user->key(), $ENV{REMOTE_ADDR});
    warn $user->key(), $ENV{REMOTE_ADDR}, ": No cookie - attempting argument redirect\n";
    my $logintoken = urlescape(CounterCGI::logintoken($user));
    if ($tourl =~ /\?/) {
	$tourl .= "&nocookie=$logintoken";
    } else {
	$tourl .= "?nocookie=$logintoken";
    }
}
# warn "Value of tourl : $tourl\n";

# Try to set the cookies whether the user can use them or not.

if ($user->{login}) {
    $admincookie = $q->cookie(-name => "adminuser",
			  -value => $user->{login},
			  -expires => "+24h",
			  -path => "/",
			  -domain => $domain);
    $x = $q->header(-cookie=>$admincookie);
    $x =~ s/[\r\n]+$//; # remove the header-terminating blankline
    print $x;
    print "\r\n";
}

$x = $q->header(-cookie=>$logincookie);
$x =~ s/[\r\n]+$//; # remove the header-terminating blankline
print $x;
print "\r\n";
# Note - redirect() terminates the header...
$y = $q->redirect($tourl);
print $y;
print <<EoF;
<html><head>
<title>You should have been redirected</title>
</head><body>
You should not have seen this. You should have been at
<a href="$tourl">$tourl</a>.
<p>
Please report the bug to webmaster&#x40;counter.li.org.
</body>
</html>
EoF

# That's all...

# URL-encode data
# code stolen from Perl 5.6.1 CGI::Util module
sub urlescape {
  my $toencode = shift;
  return undef unless defined($toencode);
  $toencode=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
  return $toencode;
}
